package com.warren.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.warren.annotation.ControllerEndpoint;
import com.warren.response.Result;
import com.warren.system.entity.Log;
import com.warren.system.service.LogService;
import com.warren.system.vo.LogVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.ObjectUtils;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;


/**
 * <p>
 * 操作日志表 前端控制器
 * </p>
 *
 * @author warren
 * @since 2021-04-18
 */
@RestController
@RequestMapping("/log")
@Api(value = "操作日志", tags = "操作日志接口")
public class LogController {

    @Resource
    private LogService logService;

    @ApiOperation(value = "分页操作日志")
    @PostMapping("/findLogPage")
    public Result findLogPage(@RequestParam(defaultValue = "1")Integer current,
                              @RequestParam(defaultValue = "7")Integer size,
                              @RequestBody LogVO logVO){

        //取得分页条件
        Page<Log> page = new Page<>(current,size);
        //获得wrapper
        QueryWrapper<Log> queryWrapper = getWrapper(logVO);
        //执行查询
        IPage<Log> filePage = logService.page(page,queryWrapper);

        long total = filePage.getTotal();
        List<Log> records = filePage.getRecords();
        return Result.ok().data("total",total).data("records",records);
    }

    @ControllerEndpoint(exceptionMessage = "删除操作日志失败",operation = "删除操作日志")
    @ApiOperation(value = "删除操作日志")
    @PostMapping("/deleteLogById")
    public Result deleteById(Long id){
        try {
            logService.removeById(id);
            return Result.ok();
        } catch (Exception e) {
            return Result.error();
        }
    }

    @ControllerEndpoint(exceptionMessage = "删除操作日志失败",operation = "批量删除操作日志")
    @ApiOperation(value = "批量删除操作日志")
    @PostMapping("/deleteLogsByIds")
    public Result deleteLogByIds(String ids){
        String[] idList = ids.split(",");
        logService.removeByIds(Arrays.asList(idList));
        return Result.ok().message("批量删除成功");
    }

    private QueryWrapper<Log> getWrapper(LogVO logVO){
        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
        if (logVO != null){
            if (!ObjectUtils.isEmpty(logVO.getIp())){
                queryWrapper.like("ip",logVO.getIp());
            }
            if (!ObjectUtils.isEmpty(logVO.getUsername())){
                queryWrapper.like("username",logVO.getUsername());
            }
        }
        return queryWrapper.orderByDesc("create_time");
    }
}

